﻿//----------------------------------------------
// 作者:江怀玉
// 依赖:
//       1、jQuery 
//       2、Jquery.json插件
// 说明: 将JSON数据，回传到页面
// 
// Version :V 0.1.0
// 表单操作类库
// 1、将JSON数据影射到Form里
// 2、将From的数据转换成JSON数据格式
// 3、URLEncode
// 4、数据保存操作
// 5、数据修改操作
// ----------------------------------------------------------
// 6、数据删除操作
// 7、数据查询
// 8、自定义控件增加了关键字段，用于指定搜索数据的条件关键字
// ----------------------------------------------------------

(function ($) { 
    $.JSONToForm = function (jsonString) {

        var json = jsonString;
        ///用於轉換日期格式
        json = json.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
        json = json.replace(/[BR]/g, "\n");
        var o = $.evalJSON(json);
        $.each(o, function (property, value) {
            //try {
            value = value + "";
            // find the control and set value
            if (property != "") {
                var control = $("[name='" + property + "']");
                var strValue = value.replace(/@1@1@1/g, "'");
                strValue = strValue.replace(/@2@2@2/g, '"');
                strValue = strValue.replace(/@@@@/g, "\n");
                strValue = strValue.replace(/[BR]/g, "\n");
                control.val(strValue);
                try {
                    $('#' + property).combobox('setValue', strValue);
                } catch (Error) { }
            }
            //  };
        });
    };
})(jQuery);

(function ($) {
    $.fn.JSONToForm = function (_obj) {
        //debugger
        var json="";//= jsonString;
        var o ;
        if(typeof(_obj)=="string")
        {
            json = _obj;  
            json = json.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
            o = json==""?_obj:$.evalJSON(json);
        }
        else
        {
            o=_obj;
        }
        ///用於轉換日期格式

        var controls = $(this).find('input, select, textarea, label');
        $.each(o, function (property, value) {
            //try {
            value = value + "";
            // find the control and set value
            if (property != "") {
                controls.each(function () {
                    if ($(this).attr("name") == property) {
                        //var c = this.find("[name='" + property + "']");
                        var strValue = value.replace(/@1@1@1/g, "'");
                        strValue = strValue.replace(/@2@2@2/g, '"');
                        strValue = strValue.replace(/@@@@/g, "\n");
                        strValue = strValue.replace(/\[BR\]/g, "\n");
                        //debugger
                        if(($(this).attr("ctrlType")!="" && $(this).attr("ctrlType")!= undefined) ||(  $(this).attr("ctrltype")!="" && $(this).attr("ctrltype")!= undefined ) )
                        {
                            
                            if( $(this).attr("SelectMode")=="s" || $(this).attr("selectmode")=="s"){
                               GetData($(this).attr("id"),strValue);
                            }
                            else{
                               GetMData($(this).attr("id"),strValue);
                            }
                        }
                        else
                        {
                            $(this).val(strValue);
                        }
                        try {
                            $('#' + property).combobox('setValue', value);
                        } catch (Error) { }
                    }
                });
            }
            //  };
        });
    };
})(jQuery);


//获取字典数组
function GetData(id, keyValue) {
    $this = $("#" + id);
    var entity =$this.attr("entity");//实体名称
    var key  = $this.attr("keyfield");//关键字段
    key = key ==undefined || key =="" ?"id":key;
    var condition = key+"='" + keyValue + "'";//条件
    
    var _data = null;
    if (_data == null) {
        $.ajax({
            type: "GET",
            url: "/Extend/AjaxData/DataTableJsonList.aspx",
            data: { entity: entity, condition: condition },
            async: false,
            success: function (data) {
                //debugger
                if (data == '{"total":0,"rows":}') {
                    return;
                }
                else {
                    _data = eval("(" + data + ")");
                }
            },
            error: function (e) {
                return;
            }
        }
        );
    }
    if (_data != null) {     
       $this .attr("SValue", keyValue);
       var _tField = $this.attr("displaymember");
       $this.attr("SText", _data.rows[0][_tField]);
       $this.val(_data.rows[0][_tField]);
    }

}


//获取多字典数组
function GetMData(id, keyValue) {
    var entity = $("#"+id).attr("entity");//实体名称
    var condition = "id in (select value from dbo.fn_split('" + keyValue + "',','))";//条件
    var _data = null;
    if (_data == null) {
        $.ajax({
            type: "GET",
            url: "/Extend/AjaxData/DataTableJsonList.aspx",
            data: { entity: entity, condition: condition },
            async: false,
            success: function (data) {
                //debugger
                if (data == '{"total":0,"rows":}') {
                    return;
                }
                else {
                    _data = eval("(" + data + ")");
                }
            },
            error: function (e) {
                return;
            }
        }
        );
    }
    if (_data != null) {
       var _text = "";
        $.each(_data.rows,function(index){
          _text=((_text=="")?_data.rows[index].name:(_text+","+_data.rows[index].name));
        });
        $("#" + id).attr("SText", _text);
        $("#" + id).val(_text);
    }

}


//当前用户默认属性值
(function ($) {
    $.fn.JSONToFormDefaultPropertyValues = function (jsonString) {

        var json = jsonString;
        ///用於轉換日期格式
        json = json.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
        json = json.replace(/[BR]/g, "\n");
        var o = $.evalJSON(json);
        $.each(o, function (property, value) {
            //try {
            value = value + "";
            // find the control and set value
            if (property != "") {
                var control = $("[name='" + property + "']");
                
                var strValue = value.replace(/@1@1@1/g, "'");
                strValue = strValue.replace(/@2@2@2/g, '"');
                strValue = strValue.replace(/@@@@/g, "\n");
                strValue = strValue.replace(/[BR]/g, "\n");
                control.val(strValue);
                try {
                    $('#' + property).combobox('setValue', strValue);
                } catch (Error) { }
            }
            //  };
        });
    };
})(jQuery);

//Labels模式
(function ($) {
    $.fn.LabelModel = function () {
        if(getPar1("entity").indexOf("Bpm_")>-1){
        var DefaultPropertyName=["Proposer","Filiale","DeptName","PostName","CreatedTime","PhraseText","JoinDate"]
        $.each(DefaultPropertyName, function (property, value) {
            if (value != "") {
                var control = $("[name='" + value + "']");
                
                control.css("border-bottom-style","none"); 
                control.css("border-bottom-color","transparent"); 
                control.css("border-right-style","none"); 
                control.css("border-top-color","transparent"); 
                control.css("border-top-style","none"); 
                control.css("border-right-color","transparent"); 
                control.css("border-left-style","none"); 
                control.css("border-left-color","transparent"); 
                control.css("background","#f2f8ff"); 

                control.attr("readonly", "readonly");
                //control.parent().parent().remove();
            }
        });
        }
    };
})(jQuery);

//只读模式
(function ($) {
    $.fn.ReadonlyModel = function (_obj) { 
        $.each(_obj, function (property, value) {
            if (value != "") {
                var control = $("[name='" + value + "']");
                 
                if (typeof (control[0]) != "undefined")
                {
                  if(control[0].nodeName=='INPUT'){control.attr("readonly", "readonly");}
                  else{control.attr("disabled", "disabled");}

                  var strType=control[0].getAttribute("type");
                   if( typeof strType!= "undefined")
                   {
                        switch(strType)
                        {
//                        case 'Date':
//                                //control[0].onclick='';
//                                
//                                $(control[0]).attr("onclick", "");
//                                var oldclass= $(control[0]).attr("class");
//                                if( typeof oldclass!= "undefined")
//                                {
//                                        var reg=new RegExp("Wdate","g"); //创建正则RegExp对象    
//                                        var stringObj=oldclass;    
//                                        var newstr=stringObj.replace(reg," ");   
//                                        //control[0].class=newstr;
//                                         $(control[0]).attr("class", newstr);
//                                       
//                                }
//                              break;
//                        case 'Time':
//                              $(control[0]).attr("class"," ");
//                              break;
                        case 's':
                               var btnSControl = $("[id='btn" + value + "']");
                               btnSControl.attr("disabled", "disabled");
                              break;
                        case 'pos':
                               var btnposControl = $("[id='btn" + value + "']");
                               btnposControl.attr("disabled", "disabled");
                              break;
                        case 'dep':
                               var btndepControl = $("[id='btn" + value + "']");
                               btndepControl.attr("disabled", "disabled");
                              break;
                        case '6':
                              var btn6Control = $("[id='btn" + value + "']");
                               btn6Control.attr("disabled", "disabled");
                              break;
                        case '5':
                               var btn5Control = $("[id='btn" + value + "']");
                               btn5Control.attr("disabled", "disabled");
                              break;
                  
                        }
                   }

                }
               
            }
        });
    };
})(jQuery);





//隐藏模式
(function ($) {
    $.fn.HideModel = function (_obj) {
    
        $.each(_obj, function (property, value) {
            if (value != "") {
                var control = $("[name='" + value + "']");
                control.parent().parent().remove();
            }
        });
    };
})(jQuery);


//隐藏模式
(function ($) {
    $.fn.HideTableModel = function (_obj,TableName) {

       var datTable=document.getElementById(TableName);
        $.each(_obj, function (property, value) {
            if (value != "") {
                    var CellNo=0;
                   var HeaderRow=datTable.rows[0];
                  for(var i=0;i<datTable.rows.length;i++){
                    var _row=datTable.rows[i];
                   
                    var cells=_row.cells;   
                    for(var j=0;j<cells.length;j++)
                    {
                        if(cells[j].firstChild.id==value)
                        {
                          CellNo=j;
                          _row.deleteCell(j);
                        }
                    }
                    }
                    HeaderRow.deleteCell(CellNo);
                    
            }
        });
    };
})(jQuery);



//必填模式
(function ($) {
    $.fn.RequiredModel = function (_obj) {    
    

        $.each(_obj, function (property, value) {
            if (value != "") {
                var control = $("[name='" + value + "']");
                control.attr("requireType", "1");
                //$(control.parent()[0]).append('<span style="vertical-align:middle;color:Red;font-weight:bold">*</span>');

                 $(control.parent()[0]).append('<font color="Red">*</font>');

                //requireType=1
                //control.parent().parent().remove();
            }
        });
    };
 })(jQuery);




var anArray = ['one', 'two', 'three'];
$.each(anArray, function (n, value) {
    //do something here   
    //alert(n+' '+value);   
});   


///克隆对象
(function ($) {
    $.fn.Clone = function (o1, o2) {
        $.each(o1, function (property, value) {
            if (property != "") {
                eval("o2." + property + "='" + value + "'");
            }
        });
    };
})(jQuery);


///清理对应该控件
(function ($) {
    $.fn.clear = function () {
        var controls = $(this).find('input, select, textarea');
        controls.each(function () {
            $(this).val('');
        });
    }
})(jQuery);

function repalceChars(value) {
    if (value.toString().indexOf("@1@1@1", 0) > 0) {
        value = value.toString().replace("@1@1@1", "'");
        return repalceChar(value);
    }
    else {
        return value;
    }
}

function repalceChar(value) {
    if (value.toString().indexOf("@@@@", 0) > 0) {
        value = value.toString().replace("@@@@", "\n");
        return repalceChar(value);
    }
    else {
        return value;
    }
}

//$.fn.List = function(o) {
//    alert("test" + o);
//    var defaults = {
//        ipt: this,
//        evt: "click"
//    };
//    if (o) {
//        $.extend(defaults, o);
//    }

//}
//var select;
//var items;
//(function ($) {
//    $.fn.com = function (_5a) {
//        _5a = _5a || {};
//        var select = this;
//        $.get(_5a.url, function (data, textStatus) {
//            //alert(data);
//            var list;
//            list = eval('(' + data + ')');
//            for (var o in list) {
//                var v = eval("list[o]." + _5a.valueField);
//                var t = eval("list[o]." + _5a.textField);
//                select[0].options.add(new Option(t, v));
//            }
//        });
//    };
//})(jQuery);

(function ($) {
    $.fn.com = function (_5a) {
        _5a = _5a || {};
        var select = this;
        $.get(_5a.url, function (data, textStatus) {
            //alert(data);
            var list;
            list = eval('(' + data + ')');
            var i =0;
            for (var o in list) {

                var v = eval("list[o]." + _5a.valueField);
                var t = eval("list[o]." + _5a.textField);
                select[0].options.add(new Option(t, v));
                i++;
            }
        });
    };
})(jQuery);

function IsRate(v) {
    var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字     //判断正整数 /^[1-9]+[0-9]*]*$/   
    if (re.test(v)) {
        return true;
    }
    re = /^[1-9]+[0-9]*]*$/;
    if (re.test(v)) {
        return true;
    }
    return false;
} 

// 数据绑定
(function ($) {
    $.fn.comBind = function (list, v, t) {

        var select = this;
        var obj = null;
        if (typeof (list) == "string") {
            obj = eval(list);
        }
        else {
            obj = list;
        }
        var i =0;
        for (var o in obj) {

            var v1 = eval("obj[o]." + v);
            var t1 = eval("obj[o]." + t);
            if(v1==undefined)
            {
                i++;
                continue;
            }
            i++;
            if (select[0] == undefined) {
                continue;
            }
            if(select[0].options!=undefined){
               select[0].options.add(new Option(t1, v1));
            }
       }
    };
})(jQuery);


//
(function ($) {
    $.encodeURI = function (zh) {
        if (window.RegExp && window.encodeURIComponent) {
            return encodeURIComponent(zh);
        }
        return zh;
    };
})(jQuery);



$.fn.extractObject = function () {
    //debugger
    var accum = {};
    function add(accum, namev, value) {
        if (namev.length == 1) {
            if (namev[0] != "") {
                accum[namev[0]] = $.encodeURI(value);
            }
        }
        else {
            if (accum[namev[0]] == null)
                accum[namev[0]] = {};
            add(accum[namev[0]], namev.slice(1), $.encodeURI(value));
        }
    };

    this.find('input, textarea, select').each(function () {
        try {
            if ($(this).attr("convert") != "unconvert") {
                if($(this).attr("ctrlType")!="" && $(this).attr("ctrlType")!= undefined )
                {
                    debugger
                     add(accum, $(this).attr('name').split('.'), $.trim($(this).attr("SValue")));
                }else{
                     add(accum, $(this).attr('name').split('.'), $.trim($(this).val()));
                     }
            }
        } catch (Error) { }
    });
    return accum;
};


// 迟到 ，早退，缺勤，休假，年假，事假，有薪假，
//将区域Form值传给对象
//使用样例:
//$("#deptTable").SetFormValueToObject(instance[0]);
//------------------------------------------------------
$.fn.SetFormValueToObject = function (obj) {
    //debugger
    this.find('input, textarea, select').each(function () {
        try {
            var name = $(this).attr('name').split('.');
            var v = $.trim($(this).val())
             if($(this).attr("ctrlType")!="" && $(this).attr("ctrlType")!= undefined )
             {
                v = $(this).attr("SValue");
             }
            //eval("obj." + name + "='" + v + "'"); 
            if (v.indexOf("\r\n") > -1) {
                obj[name] = v.replace(/\r\n/g, "\\\\r\\\\n").replace(/"/g,"\\\\\"");
            }
            else {
                obj[name] = v.replace(/"/g,"\\\"");
            }
        } catch (Error) { }
    });
}

$.fn.SetControlReadOnly = function () {
    this.find('input, textarea, select,button').each(function () {
        $(this).attr('disabled', 'disabled');
    });
}

$.fn.EventBind = function (e) {
    $(e).bind("blur", function () {
        $(e).attr("name")
    }
    )
}


function gettrinput(id, index) {
    var accum = {};
    function add(accum, namev, value) {
        if (namev.length == 1) {
            if (namev[0] != "") {
                accum[namev[0]] = $.encodeURI(value);
            }
        }
        else {
            if (accum[namev[0]] == null)
                accum[namev[0]] = {};
            add(accum[namev[0]], namev.slice(1), $.encodeURI(value));
        }
    };
    $("#" + id + " tr:not(:first)").each(function () {
        //abc = parseFloat(abc).add(parseFloat($("td:nth-child(" + index + ") input", this).val()));
        try {
            var name = $("td:nth-child(" + index + ") input, textarea, select", this).attr('name');
            add(accum, name.split('.'), $("td:nth-child(" + index + ") input", this).val());
        } catch (Error) { }
    });
    return accum;
}

function settrinput(id, index, arr) {
    $("#" + id + " tr:not(:first)").each(function () {
        try {
            var name = $("td:nth-child(" + index + ") input, textarea, select", this).attr('name');
            $("td:nth-child(" + index + ") input", this).val(eval("arr." + name));
        } catch (Error) { }
    });
}

//加法函数，用来得到精确的加法结果 
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 
//调用：accAdd(arg1,arg2) 
//返回值：arg1加上arg2的精确结果 
function accAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
}
//给Number类型增加一个add方法，调用起来更加方便。 
Number.prototype.add = function (arg) {
    return accAdd(arg, this);
}

function cal(id, index) {
    var total = 0;
    var t = parseFloat($("#Total" + index).val());
    var str;
    $("#" + id + " tr:not(:first)").each(function () {
        try {
            //var name = $("td:nth-child(" + index + ") input, textarea, select", this).attr('name');
            //$("td:nth-child(" + index + ") input", this).val("1");
            var v = $("td:nth-child(" + index + ") input", this).val();
            str = str + v + ":";
            if (v === "" || v === undefined) {
                total = total.add(0);
            }
            else {
                var n = parseFloat(v);
                total = total.add(isNaN(n) ? 0 : n);
            }
        } catch (Error) { }
    });
    $("#Total" + index).val(total);
    //alert(str);

}
//function setValue(n, input, arr) {
//    var filter = $.grep(arr, function(value) {
//        return value.name == v;
//    });
//    if (filter.length > 0) {
//        input.valueOf(filter[0].name);
//    }
//} 
/// ------------------------------------------
/// 设置输入控件为只读
/// ------------------------------------------
$.fn.setInputReadOnly = function (bl) {
    this.find('input, textarea, select,button').each(function () {
        $(this)[0].readOnly = bl;
        
        var strType = $(this).attr("type");
        if (strType == "button") {
            if (bl) {
                $(this).attr("disabled", "disabled");
            } else { $(this).attr("disabled", ""); }
        }
        // alert($(this)[0].name);
    });
}

$.fn.removeReadOnly = function () {
    $(this).removeAttr("disabled");
    $(this).removeAttr("disabled");
}

/// ------------------------------------------
/// 设置输入控件数字控件
/// ------------------------------------------
$(document).ready(function () {
    $('input[controlType=number]').keypress(function (event) {
        var keyCode = event.which;
        if (keyCode == 46 || (keyCode >= 48 && keyCode <= 57)) {
            return true;
        }
        else {
            alert('请输入数字');
            return false;
        }
    }).focus(function () {
        this.style.imeMode = 'disabled';
    });
});
///------------------------------------------------------------
/// 用于通用的数据保存操作
///------------------------------------------------------------
$.fn.SaveData = function (url, entity, mydata) {

    var strUrl = url + "?r=" + Math.random() + "&entity=" + entity + "&json=" + encodeURI(mydata);
    this.location = strUrl;
    //window.open(strUrl);
    $.get((strUrl), function (data, textStatus) {
        if (data == "1") {
            if (typeof (parent.LoadData) != "undefined") {
                parent.LoadData();
            }
        }
        //        else {
        //            alert("數據保存失败");
        //        }
    });
};
///------------------------------------------------------------
/// 用于通用的数据保存操作
///------------------------------------------------------------
$.fn.SaveData = function (url, entity, mydata, action) {

    var strUrl = url + "?r=" + Math.random() + "&entity=" + entity + "&json=" + encodeURI(mydata) + "&action=" + action;
    this.location = strUrl;
    //window.open(strUrl);
    $.get((strUrl), function (data, textStatus) {
        if (data == "1") {
            if (typeof (parent.LoadData) != "undefined") {
                parent.LoadData();
            }
        }
        //        else {
        //            alert("數據保存失败");
        //        }
    });
};
//$.fn.SaveData = function (url, entity, mydata) {
//    var strUrl = url + "?entity=" + entity + "&json=" + mydata;
//    $.get(strUrl, function (data, textStatus) {
//        //alert(data);
//        if (data == "1") {
//            $.messager.alert('提示', '數據保存成功!', 'info');
//            $('#w').window('hide');
//            var urls = '../AjaxData/JSONList.aspx?type=1&entity=' + entity + '&n=' + Math.random();
//            if (entity == "E_Newtopic")
//            { urls = '../AjaxData/TopicList.aspx?entity=' + entity + '&n=' + Math.random(); }
//            $('#tt').datagrid({
//                url: urls
//            });
//            if (typeof (initdatarow) == "function") {
//                window.document.location = window.document.location;
//                //initdatarow();
//            }
//        }
//        else {
//            $.messager.alert('提示', data, 'info');
//        }
//    });
//};
$.fn.SaveData1 = function (url, entity, mydata, fn) {
    var strUrl = url + "?entity=" + entity + "&json=" + mydata;
    $.get(strUrl, function (data, textStatus) {
        //alert(data);
        if (data == "1") {
            $.messager.alert('提示', '數據保存成功!', 'info');
            if (typeof (fn) == "function") {
                fn();
            }
        }
        else {
            $.messager.alert('提示', data, 'info');
        }
    });
};

///获取实体对象
function getNewInstance(entity){
    var instnace = null;
    $.ajax({
                type : "GET",
                url:"/Extend/ajaxdata/DataTableJSONList.aspx",
                data:{entity:entity,action:"getInstance"},
                async:false,
                success:function(data){
                        instnace = eval("("+data+")");
                    },
                    error: function(e){
                        return;    
                    }
                }
              );
    
}

$.fn.SaveDataProject = function (url, entity, mydata) {
    var strUrl = url + "?entity=" + entity + "&json=" + mydata;
    $.get(strUrl, function (data, textStatus) {
        //alert(data);
        if (data == "1") {
            $.messager.alert('提示', '數據保存成功!', 'info');
            $('#w').window('hide');

        }
        else {
            $.messager.alert('提示', data, 'info');
        }
    });
};

$.fn.DeleteData = function (url, entity, mydata) {
    var strUrl = url + "?entity=" + entity + "&json=" + mydata + "&action=delete";
    $.get(strUrl, function (data, textStatus) {
        //alert(data);
        if (data == "1") {
            $.messager.alert('提示', '數據刪除成功!', 'info');
        }
        else {
            $.messager.alert('提示', data, 'info');
        }
    });
};

var intervalID = 0;
function f_start() {
    intervalID = window.setInterval("logout()", 2000);
}

$.fn.logon = function (u, p) {
    window.clearInterval(intervalID);
    var url = "AjaxData/logon.aspx?loginname=" + u + "&loginpass=" + p + "&n=" + Math.random();
    $.get(url, function (data, textStatus) {
        if (data == "1") {
            window.location = "paltform.aspx"
        }
        else {
            $.messager.alert('提示', '用戶不存在或者密碼錯誤，請重試!', 'info');
        }
    });
};


///----------------------------------------------------
///编辑
///----------------------------------------------------
function Edit(w, t) {
    var w1 = "w";
    if (typeof (w) != undefined) {
        w1 = w;
    }
    var t1 = "tt";
    if (typeof (t) != undefined) {
        t1 = t;
    }
    open1();
    var selected = $('#' + t1).datagrid('getSelected');
    if (selected != null) {
        $.JSONToForm($.toJSON(selected));
    }
    //alert(selected.MenuID + ":" + selected.ParentID);
}

///-----------------------------------------------------
///
///-----------------------------------------------------
function Delete(w, t, keyword) {
    var ids = [];
    var rows = $('#tt').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(eval('rows[i].MenuID'));
    }
    var s = ids.join(',');
    var url = "../AjaxData/SaveData.aspx";
    var entity = "E_Menu";
    $('#w').DeleteData(url, entity, s);

}

function ReloadData() {
    $('#tt').datagrid({
        url: '../AjaxData/JSONList.aspx?n=' + Math.random()
    });
}

////------------------------------------------------------
////打开默认窗口   2012-12-28 何扬广, 去掉影响原生方法的方法
////------------------------------------------------------
//function open1() {
//    if (typeof (parent.myEdit) == "function") {
//        parent.myEdit('HtmlWindows/Edit.aspx', "Post", "0");
//    }
//    else {
//        open('w');
//    }
//}

////-------------------------------------------------------
//// 打开编辑窗口
////-------------------------------------------------------
//function open(w) {
//    $('#' + w).window('open');
//    //清空表单
//    $('#ff').form('clear');
//}

//function open(w) {
//    $('#' + w).window('open');
//    //清空表单
//    $('#ff').form('clear');
//}


////-------------------------------------------------------
//// 关闭编辑窗口
////-------------------------------------------------------
//function close(w) {
//    $('#' + w).window('close');
//}

//var _mytest;
//function mytest() {
//    var url = "../AjaxData/JSONList.aspx?n=" + Math.random();
//    $.get(url, function(data, textStatus) {
//        _mytest = eval(data);
//        alert(_mytest.toString());
//        //        if (data == "1") {
//        //            window.location = "paltform.aspx"
//        //        }
//        //        else {
//        //            $.messager.alert('提示', '用戶不存在或者密碼錯誤，請重試!', 'info');
//        //        }
//    });
//}
///

///
/// 用於獲取當前用戶信息
///
var user;
function InitUser() {

    $.get("../AjaxData/GetUserInfo.aspx", function (data, textStatus) {
        //alert(data);
        user = eval('(' + data + ')');
    });
}

function out() {

    $.get("../AjaxData/GetUserInfo.aspx", function (data, textStatus) {
        //alert(data);
        user = eval('(' + data + ')');
    });
}

function ChangePassword(password) {
    $.get("/AjaxData/changepassword.aspx?password=" + password, function (data, textStatus) {
        if (data == "0") {
            $.messager.alert('提示', '密碼己修改成功!', 'info');
            close('w');
        }
        else {

        }
    });
}

function logout() {
    $.get("logout.aspx", function (data, status) { var i = 0; });
    //setTimeout(logout, 1000);
}


function ViewDoc(file) {
    if (file == "") {
        $.messager.alert('提示', '沒有文檔!', 'info');
        return;
    }
    parent.viewdoc(getUrl() + file);
}



function vd(i) {
    var file = $('#DocFile' + i).val();
    ViewDoc(file);
}

function getUrl() {
    return "http://" + document.location.host;
}

function getPar(source, name) {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(source)) return RegExp.$2; return "";
}

function getPar1(name) {
    var _url = "http://" + document.location;
    return getPar(_url, name);
}

//var dataQuery = function() {
//dataQuery..Condtion = "";
//}
//var Q = new dataQuery();
//Q.c
function Encrypt(str, pwd) {
    if (str == "") return "";
    str = escape(str);
    if (!pwd || pwd == "") { var pwd = "1234"; }
    pwd = escape(pwd);
    if (pwd == null || pwd.length <= 0) {
        alert("Please enter a password with which to encrypt the message.");
        return null;
    }
    var prand = "";
    for (var I = 0; I < pwd.length; I++) {
        prand += pwd.charCodeAt(I).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));

    var incr = Math.ceil(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    if (mult < 2) {
        alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
        return null;
    }
    var salt = Math.round(Math.random() * 1000000000) % 100000000;
    prand += salt;
    while (prand.length > 10) {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for (var I = 0; I < str.length; I++) {
        enc_chr = parseInt(str.charCodeAt(I) ^ Math.floor((prand / modu) * 255));
        if (enc_chr < 16) {
            enc_str += "0" + enc_chr.toString(16);
        } else
            enc_str += enc_chr.toString(16);
        prand = (mult * prand + incr) % modu;
    }
    salt = salt.toString(16);
    while (salt.length < 8) salt = "0" + salt;
    enc_str += salt;
    return enc_str;
}

function Decrypt(str, pwd) {
    if (str == "") return "";
    if (!pwd || pwd == "") { var pwd = "1234"; }
    pwd = escape(pwd);
    if (str == null || str.length < 8) {
        alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
        return;
    }
    if (pwd == null || pwd.length <= 0) {
        alert("Please enter a password with which to decrypt the message.");
        return;
    }
    var prand = "";
    for (var I = 0; I < pwd.length; I++) {
        prand += pwd.charCodeAt(I).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
    var incr = Math.round(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    var salt = parseInt(str.substring(str.length - 8, str.length), 16);
    str = str.substring(0, str.length - 8);
    prand += salt;
    while (prand.length > 10) {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for (var I = 0; I < str.length; I += 2) {
        enc_chr = parseInt(parseInt(str.substring(I, I + 2), 16) ^ Math.floor((prand / modu) * 255));
        enc_str += String.fromCharCode(enc_chr);
        prand = (mult * prand + incr) % modu;
    }
    return unescape(enc_str);
}

$.extend({ getUrlVars: function () { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }, getUrlVar: function (name) { return $.getUrlVars()[name]; } });



// 用于扩展outerHTML属性
//alert(!$.browser.msie);
if (!$.browser.msie) {
   
    if (typeof (HTMLElement) != "undefined" && !window.opera) {
        HTMLElement.prototype.__defineGetter__("outerHTML", function () {
            var a = this.attributes, str = "<" + this.tagName, i = 0; for (; i < a.length; i++)
                if (a[i].specified)
                    str += " " + a[i].name + '="' + a[i].value + '"';
            if (!this.canHaveChildren)
                return str + " />";
            return str + ">" + this.innerHTML + "</" + this.tagName + ">";
        });
        HTMLElement.prototype.__defineSetter__("outerHTML", function (s) {
            var r = this.ownerDocument.createRange();
            r.setStartBefore(this);
            var df = r.createContextualFragment(s);
            this.parentNode.replaceChild(df, this);
            return s;
        });
        HTMLElement.prototype.__defineGetter__("canHaveChildren", function () {
            return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());
        });
    }
}
///用于扩展
Array.prototype.Indexof = function (val) {
    for (var i = 0; i < this.length; i++) { if (this[i] == val) { return i; } }
    return -1;
}
///
Array.prototype.REMOVE = function (val) { for (var i = 0; i < this.length; i++) { if (this[i] == val) { this.splice(i, 1); break; } } }
///
function clone(myObj) {
    if (typeof (myObj) != 'object') return myObj;
    if (myObj == null) return myObj;
    var myNewObj = new Object();
    for (var i in myObj)
        myNewObj[i] = clone(myObj[i]);
    return myNewObj;
}

// added by xiexiaochun on 2012-09-10 begin
//日期合法校验
var isDateFormat = function (txt) {
    //是否为合法的日期格式:YYYY-MM-DD
    if (txt == null || txt == "") {
        return false;
    }
    else {
        var regex = /[0-9]{1,4}-[0-9]{1,2}-[0-9]{1,2}/;   //可按具体格式修改
        if (regex.test(txt)) {
            var noArr = txt.split("-");
            var year = eval(noArr[0]);
            var month = eval(noArr[1]);
            var day = eval(noArr[2]);
            if (year < 1 || month < 1 || month > 12 || day < 1 || day > 31) { return false; }
            if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) { return false; }
            if (month == 2) {
                if ((year % 4 != 0) && day > 29) {
                    return false;
                }
                if (year % 4 == 0) {
                    if (year % 100 == 0 && year % 400 != 0 && day > 29) {
                        return false;
                    }
                    else if (day > 28) {
                        return false;
                    }
                }
            }
            return true;
        }
        else {
            return false;
        }
    }
}




//验证时间(10:57:10)
var isTime = function (str) {
    var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
    if (a == null) {
        //alert(’时间格式不对’);
        return false;
    }
    if (a[1] > 24 || a[3] > 60 || a[4] > 60) {
        //alert("时间格式不对"); 
        return false
    }
    return true;
}

//获取当前行对象
function getTableRow(obj) {
    var row = $(obj).parent("td").parent("tr");
    return row;
}

/*
beginTime:"2012-09-21 06:00:00"
endTime:"2012-09-21 08:00:00"
interval ：D表示查询精确到天数的之差
interval ：H表示查询精确到小时之差
interval ：M表示查询精确到分钟之差
interval ：S表示查询精确到秒之差
interval ：T表示查询精确到毫秒之差
返回两日期的间隔值
*/
function dateDiff(interval, beginTime, endTime) {
    try {
        var beginTimes = beginTime.substring(0, 10).split('-');
        var endTimes = endTime.substring(0, 10).split('-');
        beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' + beginTime.substring(10, 19);
        endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);
        var intervalValue = (Date.parse(endTime) - Date.parse(beginTime));

        switch (interval) {
            case "D":
                intervalValue = intervalValue / 3600 / 1000 / 24
                break;
            case "H":
                intervalValue = intervalValue / 3600 / 1000
                break;
            case "M":
                intervalValue = intervalValue / 3600
                break;
            case "S":
                intervalValue = intervalValue / 1000
                break;
            case "T":
            default:
                intervalValue = intervalValue / 1
                break;
        }
        return intervalValue.toFixed(2);
    }
    catch (e) {
        return e.message;
    }
}

//校验浮点数字
function IsValidateFloat(obj) {
    $(obj).val(parseFloat($(obj).val(), 2));  //强制转换成浮点型.
    var reg = /^\d+(\.\d+)?$/;
    if (reg.test($(obj).val()) == false) {
        $(obj).val("0.0");
    }
}

//校验正整数
function IsInt(obj) {
    $(obj).val(parseInt($(obj).val()));  //强制转换整数.
    var reg = /^\d+$/; //正整数
    if (reg.test($(obj).val()) == false) {
        $(obj).val("0");
    }
}

function onMouseOverImgBtn(oImgBtn) {
    if (!oImgBtn.disabled);
    oImgBtn.className = "imgbuttonhover";
}

function onMouseOutImgBtn(oImgBtn) {
    if (!oImgBtn.disabled);
    oImgBtn.className = "imgbutton";
}

// --------------------------
// 系统自动初始化相关控件信息
// --------------------------
$(document).ready(function () {
    $(".datetime").each(function () {
        $(this).cld();
    })
});
